package cn.kgc.crowdfundingadminspringboot2.controller;

import cn.kgc.crowdfundingadminspringboot2.common.ResultEntity;
import cn.kgc.crowdfundingadminspringboot2.pojo.Menu;
import cn.kgc.crowdfundingadminspringboot2.service.MenuService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/menu")
public class MenuController {
    @Resource
    MenuService menuService;

    @ResponseBody
    @RequestMapping("/get/whole/tree")
    public ResultEntity<Menu> getWholeTree(){
// 1.查询所有的树形节点用于组装
        List<Menu> menuList = menuService.getAll();
        // 2.将List<Menu>转换为Map<Menu的id,Menu>
        Map<Integer,Menu> menuMap = new HashMap<>();
        for (Menu menu : menuList) {
            menuMap.put(menu.getId(),menu);
        }

        // 3.声明变量用于存储根节点对象
        Menu rootNode = null;

        for (Menu menu : menuList) {
            //是父节点
            if (menu.getPid()==null){
                rootNode=menu;
                continue;
            }
            //是子节点从menuMap找到父节点，并添加到父节点的子节点集合中
            menuMap.get(menu.getPid()).getChildren().add(menu);
        }
        return ResultEntity.successWithoutData(rootNode);
    }
    @RequestMapping("/to/page.html")
    public String toPage(){
        return "menu-page";
    }

}
